import React, { useRef, useState } from 'react';
import ProTable from '@ant-design/pro-table';
import ProCard from '@ant-design/pro-card';
import { connect } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import TemplateCat from './components/TemplateCat';
import { Popconfirm, message } from 'antd';
import request from '@/utils/request';
import Uploader from '@/components/Uploader';

const accepts = {
  1: '.doc,.docx',
  2: '.xlsx,.xls',
  3: '.pptx,.ppt',
};

const disableKey = { 1: true, 2: true, 3: true };

const Template = () => {
  const [cid, setCid] = useState();
  const [cType, setCType] = useState();

  const actionRef = useRef();

  const toggleShare = async (tid, isPrivate) => {
    const response = await request('/eofficeserver/api/templates/share', {
      method: 'POST',
      data: { tid, isPrivate },
    });
    if (response.success) {
      actionRef.current.reload();
    } else {
      message.error(response.msg);
    }
  };

  const columns = [
    {
      title: '模板名称',
      dataIndex: 'title',
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      width: 150,
    },
    {
      title: '操作',
      key: 'option',
      width: 180,
      valueType: 'option',
      render: (text, record) => [
        <Uploader
          key="upload"
          type="link"
          icon={false}
          action={`/eofficeserver/api/templates/upload?tid=${record.tid}`}
          afterUpload={() => actionRef.current.reload()}
          text="更新"
          accept={accepts[cType]}
        />,
        <a key="del">删除</a>,
        <Popconfirm
          key="share"
          title={`是否${record.isPrivate ? '' : '取消'}分享此模板?`}
          onConfirm={() => {
            toggleShare(record.tid, !record.isPrivate);
          }}
        >
          <a href="#">{record.isPrivate ? '' : '取消'}分享</a>
        </Popconfirm>,
      ],
    },
  ];

  const onCatSelect = (key, node) => {
    setCid(key);
    setCType(node.extra);
    actionRef.current.reload();
  };

  return (
    <PageContainer title={false}>
      <ProCard split="vertical">
        <ProCard colSpan="384px" ghost>
          <TemplateCat onSelect={onCatSelect} />
        </ProCard>
        <ProCard>
          <ProTable
            actionRef={actionRef}
            columns={columns}
            request={async (params, sorter, filter) => {
              // 表单搜索项会从 params 传入，传递给后端接口。
              const response = await request('/eofficeserver/api/templates/list', {
                params: { ...filter, ...params, cid },
              });

              if (!response.success) {
                return {
                  data: [],
                  // success 请返回 true，
                  // 不然 table 会停止解析数据，即使有数据
                  success: true,
                  // 不传会使用 data 的长度，如果是分页一定要传
                  total: 0,
                };
              }
              console.log({
                data: response.data.list,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: response.data.pagination.total,
              });
              return {
                data: response.data.list,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: response.data.pagination.total,
              };
            }}
            rowKey="tid"
            toolbar={{
              actions: [
                !disableKey[cid] && (
                  <Uploader
                    key="upload"
                    action={`/eofficeserver/api/templates/upload?cid=${cid}`}
                    afterUpload={() => actionRef.current.reload()}
                    text="上传模板"
                    accept={accepts[cType]}
                  />
                ),
              ],
            }}
            options={false}
            pagination={false}
            search={false}
          />
        </ProCard>
      </ProCard>
    </PageContainer>
  );
};

export default connect(({ template, loading }) => ({
  template,
  fetching: loading.effects['template/fetch'],
}))(Template);
